﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using RuleCode.Common;
using System.IO;
using RuleCode.WebControls;
using System.Data;      

namespace ERPTemplate.Public
{
    public partial class UpdateSort : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AssemblyClass.MyAssembly = Assembly.Load("RuleCode");

            bool typeRight =( Request["type"]=="edit"&& !string.IsNullOrEmpty ( Request["refid"]) ) || (Request ["type"]=="new");

            if (RuleCode.Common .AssemblyClass.MyAssembly!=null &&   !String.IsNullOrEmpty(Request["tablename"]) && 
                !String.IsNullOrEmpty ( Request["id"]) && !String.IsNullOrEmpty (Request["queryname"]) &&  typeRight)
            {
            }
            else
            {
                Response.Clear();
                Response.Write("您没有权限访问该页面！");
                Response.End();
            }

            if (!IsPostBack)
            {    
                InitPageData();
            }

        }

        #region 辅助方法

        /// <summary>
        /// 初始化页面的数据
        /// </summary>
        private void InitPageData()
        {

            try
            {
                string tableFullName = AssemblyClass.GetTypeFullName(Request["tablename"], typeof(RuleCode.Common.Table));
                if (!String.IsNullOrEmpty(tableFullName))
                {
                    TableNameLabel.Text = Request["tablename"];

                    RuleCode.Common.Table table = AssemblyClass.MyAssembly.CreateInstance(tableFullName) as RuleCode.Common.Table;
                    if (table.AllFields != null && table.AllFields.Count > 0)
                    {
                        DropDownList_FieldName.Items.Clear();
                        foreach (string fieldName in table.AllFields)
                        {
                            if (fieldName != "DATAAREAID")                                
                                DropDownList_FieldName.Items.Add(fieldName); 
                        }
                        if (DropDownList_FieldName.Items.Count > 0)
                            DropDownList_FieldName.SelectedIndex = 0;
                    }

                    string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
                    string queryXmlFileName = Path.Combine(queryXmlFilePath, Request["queryname"] + ".xml");
                    RuleQueryTable.CreateNewQueryXmlFile(queryXmlFileName);
                    if (Request["type"] == "edit")
                    {
                        InfoB.InnerText = "修改排序方式";
                        if (File.Exists(queryXmlFileName))
                        {
                            DataSet dSet = new DataSet();
                            dSet.ReadXml(queryXmlFileName);
                            DataTable sortDataTable = dSet.Tables[RuleQueryTable.SortingDataTableName];
                            if (sortDataTable != null)
                            {
                                DataRow[] dRows = sortDataTable.Select("ID='" + Request["refid"] + "'");
                                if (dRows.Length > 0)
                                {
                                    string fieldName = dRows[0]["字段名"].ToString();
                                    string sortDirect = dRows[0]["排序方向"].ToString();

                                    DropDownList_FieldName.SelectedIndex = -1;
                                    bool hasFound = false;
                                    for (int i = 0; i < DropDownList_FieldName.Items.Count; i++)
                                    {
                                        if (DropDownList_FieldName.Items[i].Text == fieldName)
                                        {
                                            DropDownList_FieldName.Items[i].Selected = true;
                                            hasFound = true;
                                            break;
                                        }
                                    }
                                    if (!hasFound && DropDownList_FieldName.Items.Count > 0)
                                        DropDownList_FieldName.SelectedIndex = 0;

                                    hasFound = false;
                                    DropDownList_SortDir.SelectedIndex = -1;
                                    for (int i = 0; i < DropDownList_SortDir.Items.Count; i++)
                                    {
                                        if (DropDownList_SortDir.Items[i].Value == sortDirect)
                                        {
                                            hasFound = true;
                                            DropDownList_SortDir.Items[i].Selected = true;
                                            break;
                                        }
                                    }
                                    if (!hasFound && DropDownList_SortDir.Items.Count > 0)
                                        DropDownList_SortDir.SelectedIndex = 0;
                                }
                            }
                        }
                    }
                    else {
                        InfoB.InnerText = "新建排序方式";
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(this.Page ,error.Message);
            }
        }
        #endregion

        #region 事件
        protected void Button_Cancel_Click(object sender, EventArgs e)
        {
            ClosePage();
        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {
            string queryXmlFilePath = RuleQueryTable.getXMLFileName(Request["tablename"], Request["id"]);
            string queryXmlFileName = Path.Combine(queryXmlFilePath, Request["queryname"] + ".xml");
            DataSet dSet = new DataSet();
            dSet.ReadXml(queryXmlFileName);
            DataTable sortDataTable = dSet.Tables[RuleQueryTable.SortingDataTableName];
            if (sortDataTable == null)
            {
                sortDataTable = new DataTable();
                sortDataTable.TableName = RuleQueryTable.SortingDataTableName;  
                sortDataTable.Columns.Clear();
                sortDataTable.Columns.Add("ID");
                sortDataTable.Columns["ID"].AllowDBNull = false;
                sortDataTable.Columns["ID"].DataType = typeof(int);
                sortDataTable.Columns.Add("表名");
                sortDataTable.Columns["表名"].AllowDBNull = false;
                sortDataTable.Columns.Add("字段名");
                sortDataTable.Columns["字段名"].AllowDBNull = false;
                sortDataTable.Columns.Add("排序方向");
                sortDataTable.Columns["排序方向"].AllowDBNull = false;
            }

            if (Request["type"] == "edit")
            {
                DataRow[] dRows = sortDataTable.Select("ID='" + Request["refid"] + "'");
                if (dRows.Length > 0)
                {
                    dRows[0]["字段名"] = DropDownList_FieldName.SelectedValue;
                    dRows[0]["排序方向"] = DropDownList_SortDir.SelectedValue;
                    sortDataTable.AcceptChanges();
                }
            }
            else if (Request["type"] == "new")
            {
                DataTable rangeDataTable = dSet.Tables[RuleQueryTable.RangeDataTableName];
                int sortID = sortDataTable.Rows.Count +((rangeDataTable!=null)? rangeDataTable.Rows.Count:0);
                DataRow newRow = sortDataTable.NewRow();
                newRow["ID"] = sortID;
                newRow["表名"] = Request["tablename"];
                newRow["字段名"] = DropDownList_FieldName.SelectedValue;
                newRow["排序方向"] = DropDownList_SortDir.SelectedValue;
                sortDataTable.Rows.Add(newRow);
                sortDataTable.AcceptChanges();
                if (dSet.Tables[RuleQueryTable.SortingDataTableName] == null)
                    dSet.Tables.Add(sortDataTable);
            }
            File.Delete(queryXmlFileName);
            dSet.WriteXml(queryXmlFileName);
            ClosePage();
        }


        private void ClosePage()
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseWindow", "<script type=\"text/javascript\">closeWindow();</script>", false);
        }
        #endregion
    }
}
